import * as React from "react";
import { inject, observer } from "mobx-react";
import { Modal, Upload, message } from 'antd';
import { History, Location } from 'history';
import { ColumnProps } from 'antd/lib/table/interface';
import  PublicTable  from '../../../common/PublicTable';
import  HeaderButton  from '../../../common/header-button/HeaderButton';
import  EditModal  from '../../../common/editModal/EditModal';
import { CommonData } from '../../../../basicData/data'
import ls from '../../../../util/localStorage'
import { AppStore } from '../../../../store';
import {
  pagedDatasAsync,
  upsertAsync,
  deleteAsync,
  batchDeleteAsync,
} from '../../../../basicData/api'
import { dateFormat } from '../../../../util/util'
import '../../home.less';

interface IProps {
  history: History;
  location: Location;
  children?: AudioContextLatencyCategory;
  appStore: AppStore;
}


interface State {
  searchText: string;
  visible: boolean,
  isNew: boolean,
  value: any,
  data: {
    totalCount: number,
    items: any
  }
}

//初始化state
const initialState: State = {
  searchText: '',
  visible: false,
  isNew: false,
  value: {},
  data: {
    totalCount: 0,
    items: [],
  }
};

type IState = Readonly<typeof initialState>;

@inject("appStore")
@observer
class Companys extends React.Component<IProps, IState> {
  tableRef: any
  modalformRef: any
  type: string
  state: IState = initialState;

  UNSAFE_componentWillMount() {
    this.props.appStore.onSelectChange([], []);
    this.props.appStore.pageChange(1);
  }

  componentDidMount() {
    this.type = 'Company'
    this.getData({});
  }

  /**
   * 获取列表数据
   * @param type 接口名称
   * @param param 请求数据
   */
  getData = (param: any) => {
    pagedDatasAsync(this.type, param).then ((res: any) => {
      this.setState({
        data: res.result
      })
    })
  }

  pageChange = (page: number) => {
    this.getData({
      skipCount: (page - 1) * 10,
    })
  }

  edit = (record: any) => {
    this.setState({
      isNew: false,
      visible: true,
      value: record
    })
  }

  delete = (record: any) => {
    Modal.confirm({
      title: '确认删除',
      content: `确认删除公司：【 ${record.companyName} 】？` ,
      okText: '确定',
      cancelText: '取消',
      onOk: () => {
        deleteAsync(this.type, record.id).then((res: any) => {
          if(res.success){
            this.props.appStore.pageChange(1);
            message.success('删除成功')
            this.getData({})
          }
        })
      },
    })
    
  }

  saveFormRef = (formRef: any) => {
    this.modalformRef = formRef;
  }

  handleCancel = () => {
    this.setState({
      visible: false,
    });
  }

  handleCreate = (values: any) => { 
    const param = {
      ...values,
      companyType: 0
    }
    upsertAsync(this.type, param).then((res: any) => {
      if (res.success) {
        message.success('修改成功')
        this.setState({
          visible: false
        })
        this.getData({})
      }
    })
  }

  beforeUpload = (file:any) => {
    const isLt1M = file.size / 1024 / 1024 < 1;
    if (!isLt1M) {
      message.error('图片大小不能超过1M');
    }
    return isLt1M;
  }


  render() {
    const { visible, isNew, value, data } = this.state
    const { selectedRowIds} = this.props.appStore;

    const props = {
      name: 'files',
      action: `${CommonData.BaseURL[process.env.NODE_ENV]}/api/services/app/Company/UploadImg`,
      headers: {
        Authorization: `Bearer ${ls.get('token')}`
      },
      showUploadList: false,
      beforeUpload: this.beforeUpload,
      onChange: (info: any) => {
        if (info.file.status === 'done') {
          message.success(`logo上传成功`);
          this.getData({})
        } else if (info.file.status === 'error') {
          message.error(`logo上传失败，请重试`);
        }
      },
    };

    const columns: any = [
      {
        title: '序号',
        key: "index",
        render: (text: any, record: any, index: number) => {
          return (<div>{index + 1}</div>)
        }
      },
      {
        title: '公司编码',
        dataIndex: 'companyCode',
        key: 'companyCode',
      },
      {
        title: '公司名称',
        dataIndex: 'companyName',
        key: 'companyName',
      },
      {
        title: '公司logo',
        key: 'companyLogo',
        render: (text: any, record: any) => (<div>
          {
            record.companyLogo
            ? <img src={record.companyLogo} alt="" style={{width:60,height:40,display:'block'}}/>
            : '--'
          }
        </div> ) 
      },
      {
        title: '营业执照编码',
        key: 'license',
        dataIndex: 'license',
      },
      {
        title: '创建时间',
        key: 'creationTime',
        render: (text:any, record: any, index: any) => {
          return (<div>{dateFormat(record.creationTime)}</div>)
        }
      },
      {
        title: '操作', key: 'operation', render: (text: any, record: any) => {
          return (
            <div>
              <a onClick={() => this.edit(record)}>编辑   </a>
              {/* <a onClick={() => this.delete(record)}> 删除 </a> */}
              <Upload data={() => {return {input: record.id}}} {...props}><a> 添加logo </a></Upload>
            </div>
          )
        }
      }
    ]

    const buttonConfig = {
      content: {
        isUpsert: true,
        isSearch: true,
        isDelete: true,
        isBind: false,
      },
      columns,
      searchConfig: [
        {
          type: 'input',
          name: '公司编码',
          key: 'companyCode',
        },
        {
          type: 'input',
          name: '公司名称',
          key: 'companyName',
        },
      ],
      plus: () => {
        this.setState({
          isNew: true,
          visible: true,
          value: {},
        })
      },
      sort: (value: any) => {
        this.getData({sorting: value})
      },
      search: (filter: any)=> {
        this.getData({filter:{andFilter: filter}})
      },
      reset: () => {
        this.getData({})
      },
      
      batchDelete: () => {
        batchDeleteAsync(this.type, selectedRowIds)
        .then((res: any) => {
          if(res.success){
            message.success('删除成功')
            this.getData({})
          }
        })
      },
    }

    const companyAdd = [
      { 
        type: 'input',
        name: '公司编码',
        key: 'companyCode',
        rule: { required: true, message: '请输入公司编码' }
      },
      { 
        type: 'input',
        name: '公司名称',
        key: 'companyName',
        rule: { required: true, message: '请输入公司名称' }
      },
      { 
        type: 'input',
        name: '营业执照编码',
        key: 'license',
        rule: { required: true, message: '请输入营业执照编码' }
      },
    ]

    return (
      <div>
        <HeaderButton
          {...buttonConfig}
        />
        <PublicTable
          columns={columns}
          dataSource={data}
          ref={ref => this.tableRef = ref}
        />
        <EditModal
          title={isNew ? '新增公司' : '编辑公司'}
          isNew={isNew}
          values={value}
          wrappedComponentRef={this.saveFormRef}
          visible={visible}
          onCancel={this.handleCancel}
          onCreate={this.handleCreate}
          editconfig={companyAdd}
        />
      </div>
      )
  }
}

export default Companys
